#include "rtsp.h"
#include "esp_camera.h"

extern bool get_stream_status();

static const char *TAG_RTSP = "RTSP";

static int get_jpeg_frame(rtsp_session_t *session, uint8_t **buf, size_t *len) {
    if (!get_stream_status()) return -1;

    static camera_fb_t *fb = NULL;
    fb = esp_camera_fb_get();
    if (!fb || fb->format != PIXFORMAT_JPEG) {
        ESP_LOGE(TAG_RTSP, "Frame capture failed or not in JPEG format");
        return -1;
    }

    *buf = fb->buf;
    *len = fb->len;
    session->user_ctx = fb;

    return 0;
}

static void release_jpeg_frame(rtsp_session_t *session, uint8_t *buf, size_t len) {
    camera_fb_t *fb = (camera_fb_t *)session->user_ctx;
    if (fb) esp_camera_fb_return(fb);
}

void start_rtsp_stream_server() {
    rtsp_config_t config = {
        .port = 554,
        .stream_name = "video",
        .get_frame = get_jpeg_frame,
        .release_frame = release_jpeg_frame,
        .fps = 15,
        .transport = RTSP_TRANSPORT_TCP,
        .payload_type = RTP_PAYLOAD_TYPE_MJPEG,
    };

    rtsp_handle_t server = rtsp_new_stream(&config);
    if (!server) {
        ESP_LOGE(TAG_RTSP, "Failed to create RTSP stream");
        return;
    }

    ESP_LOGI(TAG_RTSP, "RTSP MJPEG Stream Started");
    ESP_LOGI(TAG_RTSP, "Use: rtsp://<esp32_ip>:554/video");
}